#ifndef PPTPCLIENT_H
#define PPTPCLIENT_H

#include <QByteArray>
#include <QHostAddress>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QObject>
#include <QString>
#include <QTcpSocket>
#include <QVariant>
#include "PptpMessage.h"
#include "PptpSocket.h"

class PptpClient : public QObject
{
    Q_OBJECT
private:
    QVector<PptpSocket *> pptpSocketList;

public:
    explicit PptpClient(QObject *parent = nullptr);
    ~PptpClient();
    template <typename T, typename Func>
    void pptpConnect(
        QString ip, QString port, const PptpMessage &pptpRequest, T *object, Func callback);
};

template <typename T, typename Func>
void PptpClient::pptpConnect(
    QString ip, QString port, const PptpMessage &pptpRequest, T *object, Func callback)
{
    PptpSocket *pptpSocket = new PptpSocket();
    QByteArray writeMessage = pptpRequest.wrapJson();
    connect(pptpSocket, &PptpSocket::pptpConnect, [this, writeMessage, pptpSocket]()
            { pptpSocket->pptpWrite(writeMessage); });
    connect(pptpSocket,
            &PptpSocket::readCompletedSignal,
            this,
            [this, object, callback](QByteArray readMessage)
            {
                PptpSocket *pptpSocket = qobject_cast<PptpSocket *>(sender());
                PptpMessage pptpResponse;
                pptpResponse.parseJson(readMessage);
                pptpSocket->deleteLater();
                pptpSocketList.removeOne(pptpSocket);
                (object->*callback)(pptpResponse);
            });
    pptpSocket->connectToHost(ip, port);
    pptpSocketList.append(pptpSocket);
}

#endif // PPTPCLIENT_H
